<template>
  <el-row :gutter="20">
    <el-col :span="12"
      ><el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <el-form-item label="企业全称:" prop="enterpriseFullName">
          <el-input v-model="ruleForm.enterpriseFullName" />
        </el-form-item>
        <el-form-item label="企业简称:" prop="enterpriseAbbreviation">
          <el-input v-model="ruleForm.enterpriseAbbreviation" />
        </el-form-item>
        <el-form-item label="企业LOGO:" prop="enterpriseUpload">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:5039/api/Sheep/Enterimage"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="ruleForm.enterpriseUpload"
              :src="ruleForm.enterpriseUpload"
              class="avatar"
              style="width: 160px; height: 160px"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="行业标签" prop="industryLabelsId">
          <el-select
            v-model="ruleForm.industryLabelsId"
            placeholder="请选择行业标签一级"
            style="width: 190px"
            @change="gethang"
          >
            <el-option
              v-for="item in hangyeList"
              :key="item.industryLabelsId"
              :label="item.industryLabelsName"
              :value="item.industryLabelsId"
            /> </el-select
          >——
          <el-select
            v-model="ruleForm.industryId"
            placeholder="请选择行业标签二级"
            style="width: 190px"
          >
            <el-option
              v-for="item in gethangList"
              :key="item.industryId"
              :label="item.industryName"
              :value="item.industryId"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="所在区域">
          <el-select
            v-model="ruleForm.provinceId"
            placeholder="请选择省"
            clearable
            @change="getCity"
            style="width: 100px"
          >
            <el-option
              v-for="item in proviceList"
              :label="item.provinceName"
              :value="item.provinceId"
            />
          </el-select>
          ——
          <el-select
            v-model="ruleForm.cityId"
            placeholder="请选择市"
            clearable
            @change="getCountry"
            style="width: 100px"
          >
            <el-option
              v-for="item in cityList"
              :label="item.cityName"
              :value="item.cityId"
            />
          </el-select>
          ——
          <el-select
            v-model="ruleForm.countyId"
            placeholder="请选择县"
            clearable
            style="width: 100px"
          >
            <el-option
              v-for="item in countryList"
              :label="item.countyName"
              :value="item.countyId"
            />
          </el-select>
        </el-form-item>

        <div>
          <el-form-item label="详细地址:" prop="enterpriseAddress">
            <el-input v-model="ruleForm.enterpriseAddress" />
            <el-button :icon="LocationFilled" type="primary" @click="searchLocation" 
              >地图定位</el-button
            >
          </el-form-item>
          <!-- 创建地图容器 -->
          <div id="map-container" style="width: 300px;height: 300px;margin-left: 100px;"></div>
        </div>
      </el-form>
    </el-col>
    <el-col :span="8"
      ><el-form>
        <el-form-item label="企业电话:" prop="enterprisePhone">
          <el-input v-model="ruleForm.enterprisePhone" />
        </el-form-item>
    <!-- <div>
      <el-form-item label="详细地址:" prop="address">
        <el-input v-model="ruleForm.address" />
        <el-button type="primary" @click="searchLocation">地图定位</el-button>
      </el-form-item>
      <div id="map-container" style="width: 300px;height: 300px;"></div>
    </div> -->

    <!-- <el-form-item label="企业电话:" prop="phone">
      <el-input v-model="ruleForm.phone" />
    </el-form-item> -->
  

    

        <el-form-item label="统一社会信用代码:" prop="enterpriseUnified">
          <el-input v-model="ruleForm.enterpriseUnified" />
        </el-form-item>

        <el-form-item label="描述:" prop="enterpriseDescription">
          <el-input v-model="ruleForm.enterpriseDescription" type="textarea" />
        </el-form-item>

        <el-form-item label="停用企业:" prop="enterpriseDeactivated">
          <el-switch v-model="ruleForm.enterpriseDeactivated" />
        </el-form-item>

        <el-form-item label="负责人:" prop="enterpriseHead">
          <el-input v-model="ruleForm.enterpriseHead" />
        </el-form-item>

        <el-form-item label="财务负责人:" prop="enterpriseFinance">
          <el-input v-model="ruleForm.enterpriseFinance" />
        </el-form-item>

        <el-form-item label="分管负责人:" prop="enterpriseCharge">
          <el-input v-model="ruleForm.enterpriseCharge" />
        </el-form-item>

        <el-form-item label="可查看人员:" prop="enterprisePerson">
          <el-input v-model="ruleForm.enterprisePerson" />
        </el-form-item>

        <el-form-item label="核算单元:">
          <el-input @click="www()" v-model="form1.accountingUnitName">
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button :icon="SuccessFilled" type="primary" @click="submitForm(ruleFormRef)">
            保存
          </el-button>
          <el-button type="success"  :icon="Refresh" @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form></el-col
    >
  </el-row>
  <el-dialog v-model="dialogVisible" title="核算单元" width="500">
    <el-tree
      style="max-width: 600px"
      :data="data"
      :props="defaultProps"
      @node-click="handleNodeClick"
    />
    <el-button :icon="SuccessFilled" @click="Bao()">保存</el-button>
  </el-dialog>
</template>

<script lang="ts" setup>
import {
LocationFilled,SuccessFilled,Refresh
} from '@element-plus/icons-vue'
import { reactive, ref, computed, watch, onMounted } from 'vue';
import type { ComponentSize, FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import type { UploadProps } from 'element-plus';
import router from '@/router';
import axios from 'axios';
let accountingUnitName = '';
let accountingUnitId = 0;
const handleNodeClick = (data: any) => {
  console.log(data);
  accountingUnitId = data.value;
  accountingUnitName = data.label;
  console.log(accountingUnitName);
  console.log(accountingUnitId);
};

const defaultProps = {
  children: 'children',
  label: 'label',
  value: 'value',
};
const www = () => {
  dialogVisible.value = true;
};
const form1 = reactive({
  accountingUnitName: '',
});
const dialogVisible = ref(false);
const Bao = () => {
  console.log(accountingUnitName);
  form1.accountingUnitName = accountingUnitName;
  console.log(form1.accountingUnitName);
  dialogVisible.value = false;
};

const data = ref([]);
const dataTree = () => {
  axios
    .get('http://localhost:5039/api/Sheep')
    .then((res) => {
      data.value = res.data;
    })
    .catch((err) => {
      console.log(err);
    });
};

const searchLocation = () => {
  const map = new BMap.Map('map-container');
  const localSearch = new BMap.LocalSearch(map);
  localSearch.search(ruleForm.enterpriseAddress);
  localSearch.setSearchCompleteCallback((result: any) => {
    if (result && result.getCurrentNumPois() > 0) {
      const poi = result.getPoi(0);
      map.centerAndZoom(poi.point, 15);
      // 还可以添加标注等其他操作，如：
      const marker = new BMap.Marker(poi.point);
      map.addOverlay(marker);
    }
  });
};

onMounted(() => {
// 让组件挂载到DOM 在初始化地图
//container地图容器获取dom
  const map = new BMap.Map('map-container');
  const point = new BMap.Point(116.404, 39.915);
  map.centerAndZoom(point, 13);
});

const hangyeList:any = ref([]);
const gethangList:any = ref([]);
//获取行业标签下拉框一级
const getBiao = () => {
  axios
    .post('http://localhost:5039/api/Sheep/IndustryLabelsType')
    .then((res) => {
      console.log(res);
      hangyeList.value = res.data.data;
    })
    .catch((err) => {
      console.log(err);
    });
};
//获取行业标签下拉框二级
const gethang = () => {
  (ruleForm.industryId = ''),
    axios
      .post('http://localhost:5039/api/Sheep/IndustryType', {
        industryLabelsId: ruleForm.industryLabelsId,
      })
      .then((res) => {
        console.log(res);
        gethangList.value = res.data.data;
      })
      .catch((err) => {
        console.log(err);
      });
};
onMounted(() => {
  getBiao();
  dataTree();
});

const proviceList: any = ref([]); //省
const cityList: any = ref([]); //市
const countryList: any = ref([]); //县

//获取省下拉框
const getProvince = () => {
  axios
    .post('http://localhost:5039/api/Sheep/EnterpriseType')
    .then((res) => {
      proviceList.value = res.data.data;
    })
    .catch((error) => {
      console.log(error);
    });
};

//获取市下拉框
const getCity = () => {
  ruleForm.cityId = '';
  ruleForm.countyId = '';
  axios
    .post('http://localhost:5039/api/Sheep/EnterpriseType1', {
      provinceId: ruleForm.provinceId,
    })
    .then((res) => {
      cityList.value = res.data.data;
    })
    .catch((error) => {
      console.log(error);
    });
};

//获取县下拉框
const getCountry = () => {
  axios
    .post('http://localhost:5039/api/Sheep/EnterpriseType2', {
      cityId: ruleForm.cityId,
    })
    .then((res) => {
      countryList.value = res.data.data;
    })
    .catch((error) => {
      console.log(error);
    });
};

onMounted(() => {
  getProvince();
});

// const imageUrl = ref('');

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
  ruleForm.enterpriseUpload = 'http://localhost:5039' + response;
};

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('文件类型必须是JPG格式!');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('文件大小不能超过 2MB!');
    return false;
  }
  return true;
};

const formSize = ref<ComponentSize>('default');
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive({
  enterpriseFullName: '',
  enterpriseAbbreviation: '',
  enterpriseUpload: '',
  industryLabelsId: '',
  provinceId: '',
  enterpriseDeactivated: true,
  cityId: '',
  countyId: '',
  industryId: '',
  enterpriseAddress: '',
  enterprisePhone: '',
  enterpriseUnified: '',
  enterpriseDescription: '',
  enterpriseHead: '',
  enterpriseFinance: '',
  enterpriseCharge: '',
  enterprisePerson: '',
});

const locationOptions = ['Home', 'Company', 'School'];

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log('submit!');
      const pdata = {
        getEnterprise: {
          enterpriseID: 0,
          enterpriseFullName: ruleForm.enterpriseFullName,
          enterpriseAbbreviation: ruleForm.enterpriseAbbreviation,
          enterpriseUpload: ruleForm.enterpriseUpload,
          industryLabelsId: ruleForm.industryLabelsId,
          provinceId: ruleForm.provinceId,
          cityId: ruleForm.cityId,
          countyId: ruleForm.countyId,
          enterpriseAddress: ruleForm.enterpriseAddress,
          enterprisePhone: ruleForm.enterprisePhone,
          enterpriseUnified: ruleForm.enterpriseUnified,
          enterpriseDescription: ruleForm.enterpriseDescription,
          enterpriseDeactivated: ruleForm.enterpriseDeactivated,
          enterpriseHead: ruleForm.enterpriseHead,
          enterpriseFinance: ruleForm.enterpriseFinance,
          enterpriseCharge: ruleForm.enterpriseCharge,
          enterprisePerson: ruleForm.enterprisePerson,
          accountingUnitId: accountingUnitId,
          industryId: ruleForm.industryId,
        },
      };
      axios
        .post('http://localhost:5039/api/Sheep/EnterPriseAdd', pdata)
        .then((res) => {
          console.log(res);
          if (res.data.code > 0) {
            ElMessage.success('添加成功');
            router.push('/EnterListView');
          } else {
            ElMessage.error('添加失败');
          }
        });
    } else {
      console.log('error submit!', fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}));
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>

<style scoped>
.industry-selector {
  width: 300px;
  margin: 0 auto;
}

.selected-industry,
.level-one-industry,
.level-two-industry {
  margin-bottom: 20px;
}

.industry-list {
  margin-top: 10px;
}

.industry-item {
  cursor: pointer;
  padding: 5px;
  border: 1px solid #ddd;
  margin-bottom: 5px;
  display: inline-block;
}

.industry-item:hover {
  background-color: #f0f0f0;
}
</style>

<style scoped>
#map-container {
  width: 100%;
  height: 400px;
}
</style>

<style>
.el-row {
  margin-bottom: 20px;
}
.el-row:last-child {
  margin-bottom: 0;
}
.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
</style>
